// localStorage关键字
const CART_KEY = 'shopping_cart'

// 获取购物车数据
export function getCart(){
    let cartStr = localStorage.getItem(CART_KEY);
    return cartStr ? JSON.parse(cartStr) : {}
}

// 保存购物车数据
export function setCart(cart){
    localStorage.setItem(CART_KEY, JSON.stringify(cart));
}

// 添加商品到购物车
export function addToCart(product, quantity = 1){
    const cart = getCart();
    const productId = product.id;
    if (cart[productId]){
    //     商品已存在
        cart[productId].quantity += quantity;
    }else{
        cart[productId] = {
            id : productId,
            name : product.name,
            price : product.price,
            imageUrl : product.imageUrl,
            quantity : quantity
        };
    }
    setCart(cart);
}

export function removeFromCart(productId){
    const cart = getCart();
    delete cart[productId];
    setCart(cart);
}

export function updateCartQuantity(productId, quantity){
    const cart = getCart();
    if(cart[productId]){
        cart[productId].quantity = quantity;
        if(cart[productId].quantity <= 0){
            delete cart[productId];
        }
    }
    setCart(cart);
}

export function clearCart() {
    localStorage.removeItem(CART_KEY);
}
// 获取商品总数
export function getCartItemCount(){
    const cart = getCart();
    return Object.values(cart).reduce((total, item) => total + item.quantity, 0)
}

// 获取总价
export function getCartTotal(){
    const cart = getCart();
    return Object.values(cart).reduce((total, item) => total + item.quantity * item.price, 0);
}


